package com.xhtt.smart.card.server.code;

import com.xhtt.smart.card.common.enums.FunctionTypeEnum;
import com.xhtt.smart.card.common.enums.TransferTypeEnum;
import com.xhtt.smart.card.common.error.SmartCardException;
import com.xhtt.smart.card.common.msg.bean.MsgServerBean;
import com.xhtt.smart.card.common.util.HexConver;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.internal.StringUtil;

import java.util.List;

/**
 * @author wangze
 * @date 2018-07-03 15:41.
 **/
public class MessageServerDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) {

        int length = in.readableBytes();
        System.out.println("数据可读长度为：" + length);
        //读取帧头
        short frameHeaer = in.readUnsignedByte();

        System.out.println("帧头 :" + Integer.toHexString(frameHeaer));

        //读取传输码
        byte transferCode = in.readByte();

        System.out.println("传输码 :" + transferCode);

        //读取功能数
        byte functionNumber = in.readByte();

        System.out.println("功能数 :" + functionNumber);

        //读取功能码
        byte functionCode = in.readByte();

        System.out.printf("功能码 : %S \r\n", functionCode & 0xFF);


        //TODO 判断是否是心跳数据
        //读取数据长度
        short dataLength = in.readUnsignedByte();
        System.out.println("数据长度 :" + dataLength);


        byte[] data = null;
        if (dataLength > 0) {
            //读取 数据
            data = new byte[dataLength];
            in.readBytes(data);
        }
        //读取 设备码
        byte[] deviceCode = new byte[16];
        in.readBytes(deviceCode);
        //读取 设备类型
        short deviceType = in.readUnsignedByte();

        //读取校验码
        in.readByte();
        //帧尾
        in.readByte();
        MsgServerBean message = new MsgServerBean();
        message.setData(data);
        message.setDataLength(dataLength);
        message.setFunctionType(FunctionTypeEnum.getEnumByCody(functionCode));
        message.setDeviceCode(getDeviceCode(deviceCode));
        message.setDeviceType(deviceType);
        message.setTransferType(TransferTypeEnum.getByIndex(transferCode));
        list.add(message);
    }

    /**
     * 获取设备码
     *
     * @param deviceBytes
     * @return
     */

    private String getDeviceCode(byte[] deviceBytes) {

        String result = "";
        if (deviceBytes != null && deviceBytes.length > 0 && deviceBytes.length == 16) {
            result = HexConver.byteToAsciiString(deviceBytes);
        }
        if (StringUtil.isNullOrEmpty(result)) {
            throw new SmartCardException("当前请求设备码不正确");
        }
        return result;


    }
}
